package com.coderforum.community.controller;

import com.coderforum.community.dto.AccessTokenDTO;
import com.coderforum.community.dto.GiteeUser;
import com.coderforum.community.model.User;
import com.coderforum.community.provider.GiteeProvider;
import com.coderforum.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


/**
 * @Author: xuehai.XUE
 * @MailBox: xuehai.xue@qq.com
 * @Date: 2021/4/1 20:45
 * @Description:
 */
@Controller
@Slf4j
public class AuthorizedController {
    @Autowired
    private AccessTokenDTO accessTokenDTO;

    @Autowired
    private GiteeProvider giteeProvider;

    @Autowired
    private UserService userService;

    /**
     * 获取application.properties中定义的第三方应用的属性
     */
    @Value("${gitee.client.id}")
    private String clientId;
    @Value("${gitee.client.secret}")
    private String clientSecret;
    @Value("${gitee.redirect.uri}")
    private String clientRedirectUri;


    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "code") String state,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        //为accessTokenDTO对象赋值
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(clientRedirectUri);
        accessTokenDTO.setState(state);

        //将accessTokenDTO对象作为参数传入以获取用户的accessToken
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);

        //使用GetUser方法将携带的accessToken链接发送至Gitee服务器获取用户的信息
        GiteeUser giteeUser = giteeProvider.getUser(accessToken);

        if (giteeUser != null && giteeUser.getId() != null) {
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);

            response.addCookie(new Cookie("token", token));

            //重定向返回首页
            return "redirect:/";
        } else {
            log.error("callback get gitee error,{}", giteeUser);
            //登录失败，重新登录
            return "redirect:/";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
